package cn.edu.hpu.jie.util;

import java.util.Arrays;

/**
 * HMAC
 * @author Jie
 *
 */
public class HmacUtil {
	private static final byte ipad = 0x36;
	private static final byte opad = 0x5C;
	private static final int length = 64;
	
	/**
	 * 生成32位字符串的HMAC
	 * @param text
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String getHmacString(String text, String key) throws Exception {
		byte[] data = text.getBytes("UTF-8");
		byte[] keyArray = key.getBytes("UTF-8");
		
		if(keyArray.length > length) {
			keyArray = HashUtil.getHashBytes(keyArray);
		}
		
		byte[] bKeyArray = Arrays.copyOf(keyArray, length);
		
		byte[] keyIpad = new byte[length];
		byte[] keyOpad = new byte[length];
		for(int i = 0; i < length; i++) {
			keyIpad[i] = (byte) (bKeyArray[i] ^ ipad);
			keyOpad[i] = (byte) (bKeyArray[i] ^ opad);
		}
		
		byte[] firstDataArray = Arrays.copyOf(keyIpad, length + data.length);
		for(int i = 0; i < data.length; i++) {
			firstDataArray[length + i] = data[i];
		}
		
		byte[] firstHash = HashUtil.getHashBytes(firstDataArray);
		
		byte[] secondDataArray = Arrays.copyOf(keyOpad, length + firstHash.length);
		for(int i = 0; i < firstHash.length; i++) {
			secondDataArray[length + i] = firstHash[i];
		}
		return HashUtil.getHashString(secondDataArray);
	}
}
